var t = getApp(), e = new (require("../../utils/qqmap-wx-jssdk.min.js"))({
    // key: "XSYBZ-P2G34-3K7UB-XPFZS-TBGHT-CXB4U"
    key: "KJXBZ-V2PW6-N34SN-ENJTN-XP62S-ADFBT"
}), o = require("../../utils/util.js");

Page({
    data: {
        indicatorDots: !0,
        autoplay: !0,
        interval: 4e3,
        duration: 1e3,
        scrollTop: 0,
        hasLocation: !1,
        hidden: !1,
        categoryIndex: 0,
        indexCategoryList: [],
        navHeight: t.globalData.navHeight,
        countdownLeft: 0,
        countdown: {
            day: '',
            hour: '',
            minute: '',
            second: ''
        },
        newCouponExist: false,
        inNight: 0,
        tipsHeight: 0,
        notice: "当前不在配送时段，可选择次日7-22点进行配送",
        marqueePace: 1.5,//滚动速度
        marqueeDistance: 0,//初始滚动距离
        size: 14,
        interval1: 20, // 时间间隔
        msgList: ["当前不在配送时段，可选择次日7-22点进行配送", "当前不在配送时段，可选择次日7-22点进行配送"],
        listPage:1,
        categoryGoods:[],
        radioItems:[{value: '不杀'},{value:'杀好(要内脏)'},{value: '杀好(不要内脏)'}],
        radioSelect:'',
        optionsHidden:true,
        maskShow:false,
        maskShowTime:0,
        isFirstPageShow:false
    },
    onShow: function () {
        var that = this;
        that.index();
        t.setCartNum();
        var isFirstPageShow = that.data.isFirstPageShow;
        console.log(isFirstPageShow);
        !isFirstPageShow && that.indexRecommend();
        //this.getCategoryGoods(1);
        if (this.data.indexCategoryList.length > 0) {
            //this.asyncCartGoods();
        }
        if(!isFirstPageShow){
            that.setData({
                isFirstPageShow: !isFirstPageShow
            })
        }
        this.setData({
            navHeight: t.globalData.navHeight
        })
        console.log(t.globalData.navHeight);
        this.getSeckillGoods();
        wx.request({
            url: t.apiUrl("index/inNight"),
            method: "post",
            data: {},
            header: {
                "Content-Type": "application/json"
            },
            success: function (res) {
                if (res.data.code == 0) {
                    that.setData({
                        inNight: 1
                    });
                    setTimeout(() => {
                        let query = wx.createSelectorQuery();
                        query.select('.tipsNight').boundingClientRect(rect => {
                            let height = rect.height;
                            console.log(height);
                            that.setData({
                                tipsHeight: height
                            });
                        }).exec();
                    }, 300)
                } else {
                    that.setData({
                        inNight: 0,
                        tipsHeight: 0
                    });
                }
            }
        });


    },
    onLoad: function (options) {
        
        if(options != undefined && options.shareCart == 1){
           
        }
        var e = this;
        /* e.index(), */ /* setTimeout(function () {
            "" == wx.getStorageSync("region") && t.region();
        }, 2e3), */ e.getLocation();
        //e.getAddressList();
        //this.indexRecommend();
        //e.indexRecommend();
        // var scene=decodeURIComponent(options.scene);
        // console.log(scene);
        if (options.scene) {
            //console.log("has scene");
            var scene = decodeURIComponent(options.scene);
            console.log("scene is ", scene);
            wx.setStorageSync("from_id", scene);
            var arrPara = scene.split(".");
            var arr = [];
            for (var i in arrPara) {
                arr = arrPara[i].split("|");
                wx.setStorageSync(arr[0], arr[1]);
                //console.log("setStorageSync:",arr[0],"=",arr[1]);
            }

            //如果含商品id跳转到商品详情

            if(wx.getStorageSync('goodsId') > 0){
                wx.redirectTo({url: '../goods/index?objectId='+wx.getStorageSync('goodsId')});
                  
            }
        } else {
            console.log("no scene");
        }
    },
    asyncCartGoods: function () {
        var token = wx.getStorageSync("token");
        let goods = this.data.categoryGoods;
        var that = this;

        wx.request({
            url: t.apiUrl("index/getCartGoods"),
            method: "post",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": token
            },
            success: function (t) {
                if (t.data.data.length == undefined) {
                    t.data.data = [];
                }
                let cartGoods = t.data.data;
                goods.forEach((item, key) => {
                    goods[key].cart_num = 0;
                    cartGoods.forEach((val) => {
                        if (val.goods_id == item.goods_id) {
                            goods[key].cart_num = val.goods_number
                        }
                    })
                })
                that.setData({
                    categoryGoods: goods
                });

            }
        });
    },
    radioChange: function (e) {
        var items = this.data.radioItems;
        for (var i = 0; i < items.length; ++i) {
            items[i].checked = items[i].value == e.detail.value
            items[i].checked && this.setData({
                radioSelect: items[i].value
            });
        }

       this.setData({
            radioItems: items
        });
    },
    _closeMask:function(){
        this.setData({
            maskShow:false
        });
    },
    closeFloat:function(){
        this.setData({
            optionsHidden:true
        })
    },
    goodsCheckout: function (t) {
        let type = t.currentTarget.dataset.type;
        let index = t.currentTarget.dataset.index;
        console.log(index);
        let opt = t.currentTarget.dataset.opt;
        let goods = this.data.categoryGoods;
        let that = this
        if (type == 'jia') {
            if(goods[index].is_fish == 1 && opt != 1){
                goods[index].index = index;
                that.setData({
                  optionsHidden:false,
                  fishGoods:goods[index]
                })
                return false;
            }
            if(opt == 1 && that.data.radioSelect==''){
                wx.showToast({
                    title: "请选择处理方式",
                    image: "../../images/failure.png",
                    duration: 2e3
                })
                return false;
            }
            if(opt == 1 && that.data.radioSelect!=''){
               t.remarks = that.data.radioSelect;
            }
            getApp().goodsCheckout_v2(t).then((res) => {
                if (res.data.data.code == -1) {
                    wx.showModal({
                        title: '提示',
                        content: res.data.data.msg,
                        showCancel: false,
                    })
                } else {
                    goods[index].cart_num++;
                    that.setData({
                        categoryGoods: goods
                    });
                    that.setData({
                        optionsHidden:true,
                    })
                }
            })
        } else {
            goods[index].cart_num--;
            if (goods[index].cart_num > 0) {
                getApp().goodsCartUpdate(t, goods[index].cart_num)
            } else {
                getApp().goodsCartDelete(t)

            }
            this.setData({
                categoryGoods: goods
            });

        }
    },
    getSeckillGoods: function () {
        var that = this, token = wx.getStorageSync("token");
        wx.request({
            url: t.apiUrl("index/getSeckillGoods"),
            method: "POST",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": token
            },
            success: function (t) {
                that.setData({
                    secKillGoods: t.data.data,
                })
            }
        });
    },
    getAddressList: function () {
        var s = this, token = wx.getStorageSync("token");
        if (!token) {
            return;
        }
        wx.request({
            url: t.apiUrl("user/address/list"),
            method: "POST",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": token
            },
            success: function (t) {
                var tan = true;
                var a = t.data.data;

                a.forEach((item) => {
                    if (item.default == 1) {
                        tan = false
                    }
                })
                if (tan) {
                    wx.showModal({
                        title: '提示',
                        content: '请先选择地址',
                        success(res) {
                            if (res.confirm) {

                                wx.redirectTo({
                                    url: '/pages/address/index'
                                })

                            } else if (res.cancel) {
                                console.log('用户点击取消')
                            }
                        }
                    })
                }
            }
        });
    },
    onReady() {
       /*  var that = this;
        console.log('ready');
        setTimeout(() => {
            let query = wx.createSelectorQuery();
            query.select('.tipsNight').boundingClientRect(rect => {
                let height = rect.height;
                console.log(height);
                if (that.data.inNight > 0) {
                    that.setData({
                        tipsHeight: that.data.navHeight,
                        navHeight: that.data.navHeight + height
                    });
                }
            }).exec();
        }, 300) */
        /*  var length = that.data.notice.length * that.data.size; //文字长度
         var windowWidth = wx.getSystemInfoSync().windowWidth; // 屏幕宽度
         that.setData({length,windowWidth});
         that.setData({
             marqueeDistance: windowWidth
         });
         that.run1(); */
    },
    run1: function () {
        var that = this;
        that.data.countTime = setInterval(function () {
            if (-that.data.marqueeDistance < that.data.length) {
                that.setData({
                    marqueeDistance: that.data.marqueeDistance - that.data.marqueePace,
                });
            } else {
                clearInterval(that.data.countTime);
                that.setData({
                    marqueeDistance: that.data.windowWidth
                });
                that.run1();
            }
        }, 20);
    },
    index: function () {
        var e = this, o = wx.getStorageSync("token");
        var currentPosition = wx.getStorageSync("currentPosition");
        wx.request({
            url: t.apiUrl("index"),
            method: "POST",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": o
            },
            data:{
                longitude:currentPosition.longitude,
                latitude:currentPosition.latitude
            },
            success: function (t) {
                void 0 != t.data.data && e.setData({
                    index: t.data.data,
                    hidden: !0,
                    navList: t.data.data.indexNav,
                    //indexCategoryList: t.data.data.indexCategory,
                    //categoryGoods: t.data.data.indexCategoryGoods,
                    //secKillGoods: t.data.data.seckill,
                    //inNight: t.data.data.inNight,
                    newCoupons: t.data.data.newCoupons
                });
                if (t.data.data.newCouponExist > 0) {
                    e.setData({
                        newCouponExist: true
                    });
                }
                if(t.data.data.maskShow ==  1 && Date.parse(new Date()) - e.data.maskShowTime >= 3600*1000){
                    e.setData({
                        maskShow:true,
                        maskShowTime:Date.parse(new Date())
                    });
                }
                if (t.data.data.countdown > 0 && e.data.countdownLeft <= 0) {
                    e.startCountdown(t.data.data.countdown);
                    e.setData({
                        countdownLeft: t.data.data.countdown
                    });
                }
                // e.asyncCartGoods()
            }
        });
    },
    goToDetail: function (e) {
        var id = e.currentTarget.dataset.id;
        wx.navigateTo({ url: "../goods/index?objectId=" + id });
    },
    goToPlusFriday: function (e) {
        wx.navigateTo({ url: "../user/_plus_friday" });
    },
    goToHotPot: function (e) {
        wx.navigateTo({ url: "../h5/hotpot" });
    },
    goToSeckill:function(e){
        wx.navigateTo({ url: "../goods/seckill" });
    },
    goToPlusBuy: function (e) {
        wx.navigateTo({ url: "../user/plus_buy" });
    },
    addGoodsToCart: function (e) {
        var id = e.currentTarget.dataset.id;
        var gid = e.currentTarget.dataset.gid;
        var type = e.currentTarget.dataset.type;

        var token = wx.getStorageSync("token");
        if (!token) {
            wx.showModal({
                title: '提示',
                content: '请登录后继续',
                showCancel: false,
                success: function () {

                    wx.switchTab({
                        url: '../user/index',
                    })
                }

            })
            return;
        }
        wx.request({
            url: t.apiUrl("index/addGoodsToCart"),
            method: "post",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": token
            },
            data: {
                id: id,
                gid: gid,
                type: type
            },
            success: function (res) {
                if (res.data.code == 0) {
                    t.setCartNum();
                    wx.showToast({
                        title: "加入购物车成功",
                        icon: "none",
                        duration: 500
                    });
                } else {
                    wx.showToast({
                        title: res.data.data,
                        icon: "none",
                        duration: 500
                    });
                }
            }
        });

        console.log(id, gid, type);
    },
    category: function () {
        wx.getStorageSync("token");
        wx.request({
            url: t.apiUrl("category"),
            method: "post",
            header: {
                "Content-Type": "application/json"
            },
            success: function (t) {
                wx.setStorageSync("cate_data", t.data.data);
            }
        });
    },
    chooseLocation: function () {
        var o = this, n = wx.getStorageSync("token");
        wx.chooseLocation({
            success: function (a) {
                wx.setStorageSync("currentPosition", a);
                var s = a.latitude, i = a.longitude;
                o.reverseGeocoder(s,i);
            }
        });
    },
    getLocation: function () {
        var t = this;
        wx.getLocation({
            success: function (e) {
                console.log(e);
                var o = wx.getStorageSync("currentPosition");
                o ? t.transformRegion(o) : (wx.setStorageSync("currentPosition", e), t.transformRegion(e));
            },
            fail: function (e) {
                wx.showModal({
                    title: "温馨提示",
                    content: "不允许定位,会对地区商品价格有影响，请确认，去重新允许！",
                    success: function (e) {
                        e.confirm ? wx.getSetting({
                            success: function (e) {
                                wx.openSetting({
                                    success: function (e) {
                                        e.authSetting["scope.userLocation"] ? wx.getLocation({
                                            success: function (e) {
                                                var o = wx.getStorageSync("currentPosition");
                                                o ? t.transformRegion(o) : (wx.setStorageSync("currentPosition", e), t.transformRegion(e));
                                            }
                                        }) : t.getLocation();
                                    }
                                });
                            }
                        }) : e.cancel && t.getLocation();
                    }
                });
            }
        });
    },
    transformRegion: function (t) {
        var o = this, n = t.latitude, a = t.longitude;
        console.log(t);
        o.reverseGeocoder(n, a);
    },
    reverseGeocoder: function (n, a) {
        var o = this;
        e.reverseGeocoder({
            location: {
                latitude: n,
                longitude: a
            },
            success: function (t) {
                console.log(t);
                var e;
                e = (t.result.address_component.province, t.result.address_component.city, t.result.formatted_addresses.recommend),
                    o.setData({
                        hasLocation: !0,
                        address: e
                    });
                wx.request({
                    url: getApp().apiUrl("user/address/checkDeliverDistance"),
                    method: "post",
                    header: {
                        "X-ECTouch-Authorization": n
                    },
                    data: {
                        latitude: n,
                        longitude: a
                    },
                    success: function (a) {
                        if (a.data.data == 0) {
                            wx.showModal({
                                title: '提示',
                                content: '当前位置不在配送范围内',
                                showCancel:false,
                                cancelText: '取消',
                                success(res) {
                                    if (res.confirm) {
                                        //o.chooseLocation();
                                    } else if (res.cancel) {
                                    }
                                }
                            });
                        } else {
                        }
                    }
                });
            },
            fail: function (t) {
            }
        });
    },
    indexRecommend:function(){
        var that = this;
        if(that.data.noMore == true){
            return;
        }
        var currentPosition = wx.getStorageSync("currentPosition");
        wx.request({
            url: getApp().apiUrl("index/indexRecommend"),
            method: "post",
            header: {
            },
            data: {
                page: that.data.listPage,
                longitude:currentPosition.longitude,
                latitude:currentPosition.latitude
            },
            success: function (a) {
                if (a.data.code == 0) {
                    that.setData({
                        noMore:true
                    })
                } else {
                    var goodsData = that.data.categoryGoods;
                    that.setData({
                        categoryGoods:goodsData.concat(a.data.data)
                    })
                }
            }
        });
    },
    onReachBottom:function(e){
        console.log(e);
        var page = this.data.listPage;
        page++;
        this.setData({
            listPage:page
        });
        page > 1 && this.indexRecommend();
    },
    goTop: function (t) {
        wx.pageScrollTo({ scrollTop: 0 });
        this.setData({
            scrollTop: 0
        });
    },
    onPageScroll: function (s) {
        this.setData({
            indexSearch: s.scrollTop
        }), s.scrollTop > 300 ? this.setData({
            floorstatus: !0
        }) : this.setData({
            floorstatus: !1
        });

        console.log(s,getApp().globalData.screenHeight);
    },
    scroll: function (t) {
        this.setData({
            indexSearch: t.detail.scrollTop
        }), t.detail.scrollTop > 300 ? this.setData({
            floorstatus: !0
        }) : this.setData({
            floorstatus: !1
        });
        
        
    },
    onShareAppMessage: function () {
        return {
            title: "花少钱,吃好菜,让您满意的乐乐买菜",
            desc: "乐乐买菜是一个围绕着老百姓餐桌的生鲜电商结合先上线下平台",
            path: "/pages/index/index"
        };
    },
    calling: function () {
        wx.makePhoneCall({
            phoneNumber: '400-688-7977',
            success: function () {
                console.log("拨打电话成功！")
            },
            fail: function () {
                console.log("拨打电话失败！")
            }
        })
    },
    changeCategory: function (t) {
        console.log(t)

        let index = t.currentTarget.dataset.index
        this.setData({
            categoryIndex: index
        })
        let attr = t.currentTarget.id
        this.getCategoryGoods(attr);
    },
    getCategoryGoods: function (attr) {
        let e = this
        setTimeout(function () {
            let token = wx.getStorageSync('token');
            wx.request({
                url: t.apiUrl("index/getCategoryGoods"),
                method: "POST",
                header: {
                    "Content-Type": "application/json",
                    "X-ECTouch-Authorization": token
                },
                data: {
                    attr: attr
                },
                success: function (t) {
                    e.setData({
                        categoryGoods: t.data.data
                    });
                }
            });


        }, 0)

    },
    getNewCoupons: function (e) {
        let token = wx.getStorageSync('token');
        if (!token) {
            wx.showModal({
                title: '提示',
                content: '请登录后领取优惠券',
                showCancel: false,
                success: function () {

                    wx.switchTab({
                        url: '../user/index',
                    })
                }

            })
            return;
        }
        var that = this;
        wx.request({
            url: t.apiUrl("index/getNewCoupons"),
            method: "POST",
            header: {
                "Content-Type": "application/json",
                "X-ECTouch-Authorization": token
            },
            data: {
            },
            success: function (res) {
                if (res.data.data == 1) {
                    wx.showToast({
                        title: "领取成功",
                        icon: "none",
                        duration: 500
                    });
                    that.setData({
                        newCouponExist: true
                    });
                } else {
                    wx.showToast({
                        title: res.data.data,
                        icon: "none",
                        duration: 1500
                    });
                }
            }
        });
    },
    startCountdown: function (countdown) {
        var that = this;
        //serverTime = new Date(serverTime);

        var millisecond = countdown * 1000;

        var interval = setInterval(function () {
            millisecond -= 1000;
            if (millisecond <= 0) {
                clearInterval(interval);
                that.setData({
                    countdownLeft: 7200
                });
                that.startCountdown(7200);
                that.setData({
                    countdown: {
                        day: '00',
                        hour: '00',
                        minute: '00',
                        second: '00'
                    }
                });
                return;
            }
            that.setData({
                countdownLeft: countdown--
            });
            that.transformRemainTime(millisecond);
        }, 1000);
    },
    // 剩余时间(毫秒)处理转换时间
    transformRemainTime: function (millisecond) {
        var that = this;
        var countdownObj = that.data.countdown;
        // 秒数
        var seconds = Math.floor(millisecond / 1000);
        // 天数
        countdownObj.day = that.formatTime(Math.floor(seconds / 3600 / 24));
        // 小时
        countdownObj.hour = that.formatTime(Math.floor(seconds / 3600 % 24));
        // 分钟
        countdownObj.minute = that.formatTime(Math.floor(seconds / 60 % 60));
        // 秒
        countdownObj.second = that.formatTime(Math.floor(seconds % 60));
        that.setData({
            countdown: countdownObj
        });
    },
    //格式化时间为2位
    formatTime: function (time) {
        if (time < 10)
            return '0' + time;
        return time;
    },
    onOpenContact: function () {
        t.QDTracker.click();
    }
});